// 进入这个页面的时候创建websocket连接[整个页面随时使用]
import $store from '@/store/index.js';

let socket;

// 断线重连提示
function reconnectConfirm() {
    connectSocketInit()
    reconnectTime = 0
}
// 断线重连
function reconnect() {
    console.log("进入reconnect准备重新连接")
    connectSocketInit();
}







function connectSocketInit() {
    // 如果sessionStorage中没有用户信息，则跳转登录页面
    this.user = uni.getStorageSync("user");
    if (!this.user) {
        this.$router.push('/')
    }
    let that = this;
    if (typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8083/socket/" + this.user.username;
        if (socket != null) {
            socket.close();
            socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        console.log("socket:",socket)
        //打开事件
        socket.onopen = function() {
            console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function(msg) {
            console.log("收到数据====" + msg.data)
            let data = JSON.parse(msg.data)
            if (data.userNames) {
                // userNames存在则是有人登录，获取在线人员信息
                // that.userList = data.userNames
            } else {
                // userNames不存在则是有人发消息
                if(data.from=="happy" || data.to == "happy"){
                    $store.commit("setMsgListHappy", data)
                }
                else{
                    $store.commit("setMsgListCheat", data)
                }
            }
        };
        //关闭事件
        socket.onclose = function() {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            reconnect()
            console.log("websocket发生了错误");
        }
    }
}

//发送消息
 function sendMessage(message) {
    // console.log("socket:-----------------" ,socket)
    socket.send(JSON.stringify(message));
}



module.exports = {
    connectSocketInit: connectSocketInit,
    sendMessage: sendMessage,
}